import csv
import os.path
import time

DEFAULT_FILE_NAME = "./result.csv"


def is_result_file_exist(urls: list):
    """
    if not exist, init a result file by variable urls
    :param urls:  need urls list to make csv header
    :return:
    """
    flag = os.path.isfile(DEFAULT_FILE_NAME)
    if not flag:
        urls.insert(0, " ")
        headers = urls
        with open(DEFAULT_FILE_NAME, "w", encoding="utf-8", newline='') as fp:
            writer = csv.writer(fp)
            writer.writerow(headers)
        flag = 1
    return flag


def result_add_to_file(result: list):
    """

    :param result: tracingSpider's Variable temp
    :return:
    """

    # generate a formatted timestamp
    timestamp = time.time()
    time_array = time.localtime(timestamp)
    time_formatted = time.strftime("%Y/%m/%d-%H:%M:%S")
    result.insert(0, time_formatted)

    # save
    with open(DEFAULT_FILE_NAME, "a+", encoding="utf-8", newline='') as fp:
        writer = csv.writer(fp)
        writer.writerow(result)
